package com.hyacinth.forumbite.service.impl;

import com.hyacinth.forumbite.common.AppResult;
import com.hyacinth.forumbite.common.ResultCode;
import com.hyacinth.forumbite.dao.ArticleReplyMapper;
import com.hyacinth.forumbite.exception.ApplicationException;
import com.hyacinth.forumbite.model.ArticleReply;
import com.hyacinth.forumbite.service.ArticleReplyService;
import com.hyacinth.forumbite.service.ArticleService;
import com.hyacinth.forumbite.utils.StringUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Author: Yun
 * @Date: 2025/5/25
 */
@Slf4j
@Service
public class ArticleReplyServiceImpl implements ArticleReplyService {
    @Resource
    private ArticleReplyMapper articleReplyMapper;
    @Resource
    private ArticleService articleService;

    @Override
    public void create(ArticleReply articleReply) {
        if (articleReply == null || articleReply.getArticleId() == null
                || articleReply.getPostUserId() == null || StringUtil.isEmpty(articleReply.getContent())) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
        Date date = new Date();
        articleReply.setLikeCount(0)
                .setState((byte) 0)
                .setDeleteState((byte) 0)
                .setUpdateTime(date)
                .setCreateTime(date);
        //.setReplyId(null).setPostUserId(null)
        int row = articleReplyMapper.insertSelective(articleReply);
        if (row != 1) {
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
        articleService.addOneReplyCountById(articleReply.getArticleId());
    }

    @Override
    public List<ArticleReply> selectArticleReplyList(Long id) {
        if (id == null || id < 1) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        List<ArticleReply> articleReplies = articleReplyMapper.selectArticleReplyList(id);
        if (articleReplies == null) {
            articleReplies = new ArrayList<>();
        }
        return articleReplies;
    }
}
